// 用来封装fetch请求
const BASE_URL =
  "https://www.fastmock.site/mock/731d0e3c8eaaa4b9eb4bc7c16c11bed8/home";

const http = {
  get(url, params) {
    // console.log(params);
    // http://www.pudge.wang:3080/api/area/list?a=3&b=4
    // {a: 3, b: 4} -> ?a=3&b=4
    if (params) {
      const newarr = Object.keys(params).map((item) => {
        // ["a", "b"]
        return item + "=" + params[item]; // ["a=3", "b=4"]
      });
      const newstr = newarr.join("&"); // a=3&b=4
      url += "?" + newstr;
      // console.log(url);
    }

    return fetch(BASE_URL + url)
      .then((response) => response.json())
      .then((res) => {
        if (res.status === 0) {
          return res;
        }
      });
  },
  post(url, data) {
    return fetch(BASE_URL + url, {
      method: "POST",
      body: JSON.stringify(data),
      headers: new Headers({
        "Content-Type": "application/json",
      }),
    })
      .then((response) => response.json())
      .then((res) => {
        if (res.status === 0) {
          return res;
        }
      });
  },
};

export default http;
